package cn.homework.dao.impl;

import cn.homework.dao.NoticeDao;
import cn.homework.domain.Customers;
import cn.homework.domain.Notice;
import cn.homework.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ACT
 */
public class NoticeDaoImpl implements NoticeDao {
    private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

    @Override
    public List<Notice> findAllNotice() {
        String sql = "select * from notice";
        List<Notice> list = template.query(sql, new BeanPropertyRowMapper<>(Notice.class));
        return list;
    }

    @Override
    public void deleteNoticeById(String id) {
        String sql = "delete from notice where id = ?";
        template.update(sql, id);
    }

    @Override
    public void addNotice(String message, String admin) {
        String sql = "insert into notice values(?, ?, ?, ?)";
        String time = currentTime();
        String id = String.valueOf(randomNum(19));
        template.update(sql, id, message, admin, time);
    }

    @Override
    public List<Notice> findNoticeByCondition(Map<String, String[]> map) {
        String sql = "select * from notice  where 1 = 1 ";
        StringBuilder sb = new StringBuilder(sql);
        //遍历map
        Set<String> keySet = map.keySet();
        //定义参数的集合
        List<Object> params = new ArrayList<>();
        for (String key : keySet) {
            //排除条件信息
            if ("demand".equals(key)) {
                continue;
            }

            //获取values
            String values = map.get(key)[0];
            //判断是否有值
            if (values != null && !"".equals(values)) {
                //有值
                sb.append(" and " + key + " like ? ");
                params.add("%" + values + "%");
            }
        }
        sql = sb.toString();
        List<Notice> list = template.query(sql, new BeanPropertyRowMapper<>(Notice.class), params.toArray());
        return list;
    }

    private String currentTime() {
        Date data = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String string = sdf.format(data);
        return string;
    }

    private Long randomNum(int factor){
        return new Double((Math.random() + 1) * Math.pow(10, factor - 1)).longValue();
    }
}
